package org.com.liurz.iresources.activiti.process.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.apache.commons.io.IOUtils;
import org.com.liurz.iresources.activiti.process.model.BpmnModelVO;
import org.com.liurz.iresources.activiti.process.model.MyProcess;
import org.com.liurz.iresources.activiti.util.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author liurz
 * @version V1.0
 * @Package org.com.liurz.iresources.activiti.process.controller
 * @date 2021/9/30 20:33
 * @Copyright © 2020-2028
 */
@RestController
@RequestMapping("model")
@Api(tags = "流程模型接口")
public class ModelController {
	Logger logger = LoggerFactory.getLogger(ModelController.class);
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private ObjectMapper objectMapper;

	@PostMapping("/save")
	@ApiOperation("保存模型")
	public ResponseResult<String> saveBpmn(@RequestBody BpmnModelVO bpmn) {
		if (bpmn == null || StringUtils.isEmpty(bpmn.getBpmnXml()) || StringUtils.isEmpty(bpmn.getPbmnFileName())
				|| StringUtils.isEmpty(bpmn.getProcessId()) || StringUtils.isEmpty(bpmn.getProcessName())) {
			return ResponseResult.error("参数不完整");
		}
		try {
			// 在process生成pbmn文件
			// 获取项目的根路径：比如D:\git\daotie\daotie\target\classes
			// String rootFile = this.getClass().getResource("/").getPath();
			String rootFile = "D:\\code\\com.liurz.iresources.activiti\\";
			// String processFile =
			// rootFile+"/process/"+bpmn.getPbmnFileName()+".bpmn";
			String processFile = rootFile + bpmn.getPbmnFileName() + ".bpmn";
			File file = new File(processFile);
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile(); // 创建文件
			OutputStream out = new FileOutputStream(file);
			out.write(bpmn.getBpmnXml());
			// 流程读取pbmn文件，生成新的流程
			MyProcess myProcess = new MyProcess();
			myProcess.setCreateTime(new Date());
			myProcess.setPbmnFileName(bpmn.getPbmnFileName());
			myProcess.setProcessId(bpmn.getProcessId());
			myProcess.setProcessName(bpmn.getProcessName());
			myProcess.setStatus("1"); // 草稿状态
			// 记录对应的流程id、流程名称
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ResponseResult.success("成功");
	}

	@PostMapping("/deployment")
	@ApiOperation("部署模型")
	public ResponseResult<String> deployment(@RequestBody BpmnModelVO model) {
		try {
			// InputStream inputStreamBpmn =
			// this.getClass().getResourceAsStream("process/"+model.getPbmnFileName()+".bpmn");
			// InputStream inputStreamPng =
			// this.getClass().getResourceAsStream(model.getPbmnFileName()+".png");
			String rootFile = "D:\\project\\process\\" + model.getPbmnFileName() + ".bpmn";
			InputStream inputStreamBpmn = new FileInputStream(rootFile);
			ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
			Deployment deployment = processEngine.getRepositoryService()// 与流程定义和部署对象相关的Service
					.createDeployment()// 创建一个部署对象
					.name("组任务")// 添加部署的名称
					.addInputStream(rootFile, inputStreamBpmn)//
					// .addInputStream("task.png", inputStreamPng)//
					.deploy();// 完成部署
			System.out.println("部署ID：" + deployment.getId());//
			System.out.println("部署名称：" + deployment.getName());//
			return ResponseResult.error("部署模型成功");
		} catch (Exception e) {
			logger.error("部署模型异常", e);
			return ResponseResult.error("部署模型异常");
		}
	}

	public static void main(String[] args) throws FileNotFoundException {
		InputStream is = new FileInputStream(
				"D:\\code\\com.liurz.iresources.activiti\\target\\classes\\processes\\simpleProcess.bpmn");
		String xml;
		try {
			xml = IOUtils.toString(is);
			System.out.println(xml);
			byte[] bytes = xml.getBytes();
			System.out.println(bytes.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
